package com.tsite.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.tsite.dao.IGenericDAO;

@Repository
public abstract class GenericDAO<T> implements IGenericDAO<T> {

	@PersistenceContext(unitName = "entityManager")
	private EntityManager entityManager;

	private Class<T> entityClass;
	
	public EntityManager getEntityManager() {
		return entityManager;
	}

	@SuppressWarnings("unchecked")
	public GenericDAO() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.entityClass = (Class<T>) genericSuperclass
				.getActualTypeArguments()[0];
	}

	public void create(T entity) {
		entityManager.persist(entity);
	}

	public T update(T entity) {
		return entityManager.merge(entity);
	}

	public void remove(T entity) {
		entityManager.remove(entityManager.merge(entity));
	}

	public T find(Object primaryKey) {
		return entityManager.find(entityClass, primaryKey);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
	      Query q = entityManager.createQuery("SELECT e FROM " + entityClass.getName() + " e");
	      List<T> list = (List<T>) q.getResultList();
	      return list;
	}

}